﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;

namespace ERP_SaaS_WinForm.销售
{
    /// <summary>
    /// 合同修改窗口：用于展示并修改合同的基础信息。
    /// </summary>
    public partial class UpdateContract : Form
    {
        /// <summary>
        /// 合同编号
        /// </summary>
        public string ContractCode { get; set; }
        /// <summary>
        /// 合同名称
        /// </summary>
        public string ContractName { get; set; }
        /// <summary>
        /// 签订日期
        /// </summary>
        public DateTime SigningDate { get; set; }
        /// <summary>
        /// 客户名称
        /// </summary>
        public string ClientName { get; set; }
        /// <summary>
        /// 客户Id
        /// </summary>
        public int ClientId { get; set; }
        /// <summary>
        /// 发货日期
        /// </summary>
        public DateTime ShippingDate { get; set; }
        /// <summary>
        /// 合同金额或优惠金额（按页面实际含义）
        /// </summary>
        public string DiscountAmount { get; set; }
        /// <summary>
        /// 送货地址
        /// </summary>
        public string DeliveryAdder { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string ContractRemark { get; set; }
        /// <summary>
        /// 合同主键 Id
        /// </summary>
        public int ContractId { get; set; }
        /// <summary>
        /// 无参构造：仅初始化界面。
        /// </summary>
        public UpdateContract()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 通过传入的合同数据初始化窗口与控件。
        /// 字符串日期会被安全地转换为 DateTime。
        /// </summary>
        /// <param name="contractId">合同 Id</param>
        /// <param name="contractCode">合同编号</param>
        /// <param name="contractName">合同名称</param>
        /// <param name="signingDateText">签订日期（字符串）</param>
        /// <param name="clientName">客户名称</param>
        /// <param name="shippingDateText">发货日期（字符串）</param>
        /// <param name="discountAmount">合同金额/优惠金额</param>
        /// <param name="deliveryAdder">送货地址</param>
        /// <param name="contractRemark">备注</param>
        public UpdateContract(
            int contractId,
            string contractCode,
            string contractName,
            string signingDateText,
            int clientId,
            string clientName,
            string shippingDateText,
            string discountAmount,
            string deliveryAdder,
            string contractRemark)
        {
            InitializeComponent();

            ContractId = contractId;
            ContractCode = contractCode ?? string.Empty;
            ContractName = contractName ?? string.Empty;
            ClientId = clientId;
            ClientName = clientName ?? string.Empty;
            DiscountAmount = discountAmount ?? string.Empty;
            DeliveryAdder = deliveryAdder ?? string.Empty;
            ContractRemark = contractRemark ?? string.Empty;

            DateTime parsedSigningDate;
            if (!DateTime.TryParse(signingDateText, out parsedSigningDate))
            {
                parsedSigningDate = DateTime.Now;
            }
            SigningDate = parsedSigningDate;

            DateTime parsedShippingDate;
            if (!DateTime.TryParse(shippingDateText, out parsedShippingDate))
            {
                parsedShippingDate = DateTime.Now;
            }
            ShippingDate = parsedShippingDate;

            // Populate UI controls if they exist
            if (txtContractCode != null) txtContractCode.Text = ContractCode;
            if (txtContractName != null) txtContractName.Text = ContractName;
            if (txtClient != null) txtClient.Text = ClientName;
            if (txtDiscountAmount != null) txtDiscountAmount.Text = DiscountAmount;
            if (txtDeliveryAdder != null) txtDeliveryAdder.Text = DeliveryAdder;
            if (txtContractRemark != null) txtContractRemark.Text = ContractRemark;
            if (dateSigningDate != null) dateSigningDate.Value = SigningDate;
            if (dateShippingDate != null) dateShippingDate.Value = ShippingDate;

            // 绑定“选择客户”按钮事件：打开客户选择窗体，回填客户名称
            btnSelectClient.Click += (s, e) =>
            {
                using (var clientForm = new Client())
                {
                    // 以模态方式显示客户选择窗口
                    if (clientForm.ShowDialog(this) == DialogResult.OK)
                    {
                        // 期望 Client 窗体提供 SelectedClientId、SelectedClientName 属性
                        var selectedIdProp = clientForm.GetType().GetProperty("SelectedClientId");
                        var selectedNameProp = clientForm.GetType().GetProperty("SelectedClientName");
                        int selectedId = 0;
                        if (selectedIdProp != null)
                        {
                            var idObj = selectedIdProp.GetValue(clientForm);
                            if (idObj != null)
                            {
                                int.TryParse(idObj.ToString(), out selectedId);
                            }
                        }
                        var selectedName = selectedNameProp != null ? selectedNameProp.GetValue(clientForm) as string : null;

                        // 兼容：如果没有上述属性，则尝试读取 SelectedClient 对象并取其 ClientId、ClientName
                        if (selectedId == 0 || string.IsNullOrWhiteSpace(selectedName))
                        {
                            var selectedClientProp = clientForm.GetType().GetProperty("SelectedClient");
                            var selectedClient = selectedClientProp != null ? selectedClientProp.GetValue(clientForm) : null;
                            if (selectedClient != null)
                            {
                                var clientIdProp = selectedClient.GetType().GetProperty("ClientId");
                                var clientNameProp = selectedClient.GetType().GetProperty("ClientName");
                                if (clientIdProp != null)
                                {
                                    var idObj2 = clientIdProp.GetValue(selectedClient);
                                    if (idObj2 != null) int.TryParse(idObj2.ToString(), out selectedId);
                                }
                                if (clientNameProp != null)
                                {
                                    var nameObj2 = clientNameProp.GetValue(selectedClient);
                                    if (nameObj2 != null) selectedName = nameObj2.ToString();
                                }
                            }
                        }
                        if (selectedId > 0 && !string.IsNullOrWhiteSpace(selectedName))
                        {
                            ClientId = selectedId;
                            ClientName = selectedName;
                            if (txtClient != null) txtClient.Text = ClientName;
                        }
                    }
                }
            };

            // 绑定“修改”按钮事件：提交至后端
            btnUpdateContract.Click += async (s, e) =>
            {
                // 组装请求对象
                var payload = new
                {
                    ContractId = this.ContractId,
                    ContractCode = txtContractCode?.Text?.Trim(),
                    ContractName = txtContractName?.Text?.Trim(),
                    SigningDate = dateSigningDate?.Value.ToString("yyyy-MM-dd"),
                    ClientId = this.ClientId,
                    ClientName = txtClient?.Text?.Trim(),
                    ShippingDate = dateShippingDate?.Value.ToString("yyyy-MM-dd"),
                    DiscountAmount = txtDiscountAmount?.Text?.Trim(),
                    DeliveryAdder = txtDeliveryAdder?.Text?.Trim(),
                    ContractRemark = txtContractRemark?.Text?.Trim()
                };

                string apiUrl = "http://10.223.8.6:3530/api/Contract/UpdateContract";
                try
                {
                    string json = JsonConvert.SerializeObject(payload);
                    using (HttpClient http = new HttpClient())
                    {
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        var resp = await http.PostAsync(apiUrl, content);
                        var respText = await resp.Content.ReadAsStringAsync();

                        // 期望后端返回 { code, msg }
                        dynamic result = JsonConvert.DeserializeObject(respText);
                        int code = 0;
                        try { code = (int)result.code; } catch { }

                        if (resp.IsSuccessStatusCode && code == 200)
                        {
                            MessageBox.Show("修改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            string msg = null;
                            try { msg = (string)result.msg; } catch { }
                            MessageBox.Show($"修改失败：{msg ?? resp.ReasonPhrase}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"请求失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };
        }
    }
}
